import { onMounted, onUnmounted, ref } from "vue";

export default function useSpeaking() {

    let timer: NodeJS.Timeout;
    const speakingDom = ref<HTMLDivElement | null>(null);

    const isRecording = ref(false); // 正在录音中?

    function longClickFn() {

        timer = setTimeout(function () {
            // 在这里触发长按事件
            isRecording.value = true;
        }, 200); // 设置长按时间阈值，单位为毫秒
    }

    function clearTimeoutFn() {
        clearTimeout(timer);
        isRecording.value && (isRecording.value = false)
    }

    onMounted(() => {
        console.log("speakingDom.value=>   ", speakingDom.value);
        if (speakingDom.value) {
            // 添加 web 端长按事件
            speakingDom.value.addEventListener('mousedown', longClickFn);
            // 添加移动设备的长按事件 
            speakingDom.value.addEventListener('touchstart', longClickFn);
            // 取消长按事件
            speakingDom.value.addEventListener('mouseup', clearTimeoutFn);
            // 如果鼠标移出按钮区域，则取消长按事件
            speakingDom.value.addEventListener('mouseleave', clearTimeoutFn);
            speakingDom.value.addEventListener('touchend', clearTimeoutFn);
        }

    })

    onUnmounted(() => {
        if (speakingDom.value) {
            speakingDom.value.removeEventListener('mousedown', longClickFn);
            speakingDom.value.removeEventListener('touchstart', longClickFn);
            speakingDom.value.removeEventListener('mouseup', clearTimeoutFn);
            speakingDom.value.removeEventListener('mouseleave', clearTimeoutFn);
            speakingDom.value.removeEventListener('touchend', clearTimeoutFn);
        }
    })

    const isText = ref(true); // 当前是语音转文字还是键盘输入
    const changeTextFn = () => {
        isText.value = !isText.value;
    };
    return {
        speakingDom,
        isText,
        changeTextFn
    }
}